package system

import (
	"github.com/beego/beego/v2/client/orm"
	"ltbz/cultural_tourism_api/utils"
	"time"
)

// 部门表
type SysDept struct {
	DeptId     int64     `orm:"column(dept_id);pk"`
	ParentId   int64     `description:"父级部门ID"`
	DeptName   string    `description:"部门名称"`
	RootId     int64     `description:"顶层部门ID"`
	Sort       int8      `description:"排序序号"`
	Level      int8      `description:"当前层级"`
	ChildId    string    `description:"子级ID"`
	CreateTime time.Time `description:"创建时间"`
	ModifyTime time.Time `description:"修改时间"`
}

func (r *SysDept) GetSysDeptPageCount(condition string, pars []interface{}) (count int, err error) {
	o := orm.NewOrm()
	sql := `SELECT COUNT(1) AS count FROM sys_dept WHERE 1=1 `
	if condition != "" {
		sql += condition
	}
	err = o.Raw(sql, pars).QueryRow(&count)
	return
}

func (r *SysDept) GetSysDeptPage(condition string, pars []interface{}, startSize, pageSize int) (items []*SysDept, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM sys_dept WHERE 1=1 `
	if condition != "" {
		sql += condition
	}
	sql += ` ORDER BY create_time DESC LIMIT ?,? `
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

func (d *SysDept) GetDeptByName(name string) (list []*SysDept, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM sys_dept WHERE dept_name LIKE '%` + name + `%' `
	_, err = o.Raw(sql).QueryRows(&list)
	return
}

func (d *SysDept) GetDeptByDeptId(deptId int64) (item *SysDept, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM sys_dept WHERE dept_id=?`
	err = o.Raw(sql, deptId).QueryRow(&item)
	return
}

func (d *SysDept) GetDeptListByCondition(condition string, pars []interface{}, orderStr string) (list []*SysDept, err error) {
	list = make([]*SysDept, 0)
	o := orm.NewOrm()
	sql := `SELECT * FROM sys_dept WHERE 1=1 `
	if condition != "" {
		sql += condition
	}

	if orderStr == "" {
		orderStr = " ORDER BY sort ASC, create_time DESC "
	} else {
		orderStr = " ORDER BY " + orderStr
	}

	_, err = o.Raw(sql, pars).QueryRows(&list)
	return
}

type SysDeptAddReq struct {
	ParentId int64  `description:"id"`
	DeptName string `description:"部门名称"`
	Sort     int8   `description:"排序"`
}

type SysDeptEditReq struct {
	DeptId   int64  `description:"id"`
	ParentId int64  `description:"id"`
	DeptName string `description:"部门名称"`
	Sort     int8   `description:"部门名称"`
}

// 新增
func (d *SysDept) Add() (err error) {
	o := orm.NewOrm()
	_, err = o.Insert(d)
	return
}

// 删除
func (d *SysDept) DeleteByCondition(condition string, pars []interface{}) (err error) {
	o := orm.NewOrm()
	sql := ` DELETE FROM sys_dept WHERE 1=1 `
	sql += condition
	_, err = o.Raw(sql, pars).Exec()
	return

	return
}

// 修改
func (a *SysDept) Update(updateParams, whereParam map[string]interface{}) (err error) {
	to := orm.NewOrm()
	ptrStructOrTableName := "sys_dept"

	qs := to.QueryTable(ptrStructOrTableName)
	for expr, exprV := range whereParam {
		qs = qs.Filter(expr, exprV)
	}
	_, err = qs.Update(updateParams)
	return

}

type DeptListReq struct {
	DeptName string `description:"部门名称"`
	utils.PagingReq
}

type DeptListItemResp struct {
	DeptId     int64  `description:"部门ID"`
	ParentId   int64  `description:"部门父级ID"`
	DeptName   string `description:"部门名称"`
	Sort       int8   `description:"排序"`
	CreateTime string `description:"创建时间"`
	ModifyTime string `description:"最后更新时间"`
	Children   []*DeptListItemResp
}

type SysDeptListPageResp struct {
	List   []*DeptListItemResp
	Paging *utils.PagingResp
}

type DelSysDeptReq struct {
	DeptId int64 `description:"部门ID"`
}

type DeptAdminListTmpItem struct {
	SysUserId uint64 `description:"账号id"`
	RealName  string `description:"真实姓名"`
	DeptId    int64  `description:"部门id"`
	ParentId  int64  `description:"父级id"`
	DeptName  string `description:"部门名称"`
	Sort      int8   `description:"排序"`
}

type DeptAdminListItem struct {
	SysUserId uint64 `description:"账号id"`
	Name      string `description:"账号名"`
	DeptId    int64  `description:"部门ID"`
	ParentId  int64  `description:"id"`
	Sort      int8   `description:"排序"`
	Children  []*DeptAdminListItem
}

type DeptAllReq struct {
	DeptName string `description:"部门名称"`
}

func (r *SysDept) GetSysDeptAll(condition string, pars []interface{}, sort string) (items []*SysDept, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM sys_dept WHERE 1=1 `
	if condition != "" {
		sql += condition
	}
	if sort != "" {
		sql += ` ORDER BY dept_id ASC `
	} else {
		sql += ` ORDER BY create_time DESC `
	}
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

func (d *SysDept) GetDeptByDeptName(deptName string) (item *SysDept, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM sys_dept WHERE dept_name = ? `
	err = o.Raw(sql, deptName).QueryRow(&item)
	return
}

func (d *SysDept) GetDeptItemsByCondition(condition string, pars []interface{}, orderStr string) (list []*DeptListItemResp, err error) {
	list = make([]*DeptListItemResp, 0)
	o := orm.NewOrm()
	sql := `SELECT * FROM sys_dept WHERE 1=1 `
	if condition != "" {
		sql += condition
	}

	if orderStr == "" {
		orderStr = " ORDER BY sort ASC, create_time DESC "
	} else {
		orderStr = " ORDER BY " + orderStr
	}

	_, err = o.Raw(sql, pars).QueryRows(&list)
	return
}

func (d *SysDept) GetDeptItemByDeptId(deptId int64) (item *DeptListItemResp, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM sys_dept WHERE dept_id=?`
	err = o.Raw(sql, deptId).QueryRow(&item)
	return
}

func (d *SysDept) HandleDeptChildId(deptId int64) (err error) {
	var childId string
	o := orm.NewOrm()
	sql := ` WITH RECURSIVE subdept AS (
    SELECT dept_id, dept_name, parent_id
    FROM sys_dept
    WHERE parent_id = ?
    UNION ALL
    SELECT c.dept_id, c.dept_name, c.parent_id
    FROM sys_dept c
    INNER JOIN subdept sc ON c.parent_id = sc.dept_id
)
SELECT GROUP_CONCAT(DISTINCT a.dept_id) AS child_id FROM subdept AS a; `
	err = o.Raw(sql, deptId).QueryRow(&childId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}

	sql = ` UPDATE sys_dept SET child_id=? WHERE dept_id = ? `
	_, err = o.Raw(sql, childId, deptId).Exec()
	return
}
